<?php

namespace app\controller\api\contract;

use think\App;
use app\controller\api\Base;
use app\validate\contract\ContractLesseeValidate;
use app\common\repositories\contract\ContractBasicRepository;
use app\common\repositories\contract\ContractLesseeRepository;

class ContractLessee extends Base
{
    protected $repository;

    public function __construct(App $app, ContractLesseeRepository $repository)
    {
        parent::__construct($app);

        $this->repository = $repository;
    }

    public function lesseelist(int $id)
    {
        $where = $this->request->param([
            'keywords' => '',
        ]);
        $where['contract_id'] = $id;
        [$page, $limit] = $this->getPage();
        $res = $this->repository->getContractIdList($where, $page, $limit, $this->request->propertyId);
        return $this->success($res);
    }

    public function addLessee(int $id)
    {
        $param = $this->request->param([
            'username' => '',
            'mobile' => '',
            'number' => '',
            'remark' => '',
            'front_file' => '',
            'back_file' => '',
            'is_type' => '',
        ]);
        $param['is_owner'] = 2;
        $param['contract_id'] = $id;
        validate(ContractLesseeValidate::class)->scene('add')->check($param);

        /** @var ContractBasicRepository $contractBasicRepository */
        $contractBasicRepository = app()->make(ContractBasicRepository::class);
        $contractInfo = $contractBasicRepository->getSearch([])
            ->where('id', $id)
            ->field('property_id')
            ->find();
        $param['property_id'] = $contractInfo['property_id'] ?? '0';
        $this->repository->addInfo($param, $this->request->propertyId, $this->request->userId());
        return app('api_return')->success('录入成功');
    }


    public function editLessee(int $id)
    {
        $param = $this->request->param([
            'username' => '',
            'mobile' => '',
            'number' => '',
            'remark' => '',
            'front_file' => '',
            'back_file' => '',
            'is_type' => '',
        ]);
        validate(ContractLesseeValidate::class)->scene('edit')->check($param);
        $info = $this->repository->get($id);
        if (!$info) {
            return app('api_return')->error('信息错误');
        }
        $this->repository->editInfo($info, $param, $this->request->userId());
        return app('api_return')->success('更新成功');
    }

    public function delete(int $id)
    {
        if (!$this->repository->exists($id)) {
            return $this->error('数据不存在');
        }
        $info = $this->repository->get($id);
        if ($info['id'] <= 0) {
            return app('api_return')->error('数据不存在');
        }
        $res = $this->repository->batchDelete([$id], $this->request->userId());
        if ($res) {
            return $this->successText('删除成功');
        } else {
            return $this->error('删除失败');
        }
    }

}